import { useMutation } from '@tanstack/vue-query'

import { ApiCreateClass, KeyClasses, classMessage } from '@/apis/class'
import { invalidateQueries } from '@/apis/client'
import { useFetchMessage } from '@/composables/useFetchMessage'

export function useClassForm(toggleVisible: (visible?: boolean) => void) {
  const { showMessage } = useFetchMessage([classMessage])

  const { mutate, isPending } = useMutation({
    mutationFn: ApiCreateClass,
    onSettled(data, error) {
      showMessage(data?.code ?? error?.data?.code)
    },
    onSuccess() {
      invalidateQueries(KeyClasses)
      toggleVisible(false)
    }
  })

  return {
    submit: mutate,
    isPending
  }
}
